<?php

namespace App\EventListener;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;

class ExceptionListener {

    protected $event;
    protected $logger;

    public function __construct (LoggerInterface $logger) {
        $this->logger = $logger;
    }

    public function onKernelException (ExceptionEvent $event) {
        $this->event = $event;
        $this->buildException();
        $this->buildLog();
    }

    /**
     * 异常处理
     */
    private function buildException () {
        $code = $this->event->getThrowable()->getCode() != 0 ? $this->event->getThrowable()->getCode() : 500;
        $message = $this->event->getThrowable()->getMessage();
        $this->event->setResponse(json_failure($message, $code));
        $this->event->getResponse()->setStatusCode($code);
    }

    /**
     * 记录异常日志
     */
    private function buildLog () {
        $class = ($this->event->getThrowable() instanceof FatalThrowabsleError ? $this->event->getThrowable()->getOriginalClassName() : get_debug_type($this->event->getThrowable()));
        $message = json_encode($this->event->getThrowable()->getMessage(), JSON_UNESCAPED_UNICODE);
        $file = $this->event->getThrowable()->getFile();
        $line = $this->event->getThrowable()->getLine();
        $controller = $this->event->getRequest()->attributes->get('_controller');
        $uri = $this->event->getRequest()->getUri();
        $this->logger->error(sprintf('Uncaught PHP Exception %s: "%s" at %s line %s controller: %s uri: %s', $class, $message, $file, $line, $controller, $uri));
    }
}